/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.center.web.action.event;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.bean.Condition;
import com.sinodata.bsm.center.bean.EventBean;
import com.sinodata.bsm.center.bean.Page;
import com.sinodata.bsm.center.bean.RelationHelper;
import com.sinodata.bsm.center.bean.ResBean;
import com.sinodata.bsm.center.cache.ResCache;
import com.sinodata.bsm.center.purview.FunctionConstants;
import com.sinodata.bsm.center.purview.UserFunctionValidate;
import com.sinodata.bsm.center.service.event.EventService;
import com.sinodata.bsm.center.user.UserUtil;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.constants.EventConstants;
import com.sinodata.bsm.common.vo.Event;
import com.sinodata.bsm.common.vo.Res;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author dongyushi
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-5-30 下午1:51:07          dongyushi        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class HistoryEventAction extends BaseAction<Event> {

    /**
     * 
     */
    private static final long serialVersionUID = -1508700243446795699L;
    @Autowired
    private EventService eventService;
    @Autowired
    private ResCache resCache;

    public String common() {
        String format = "yyyy-MM-dd HH:mm";
        SimpleDateFormat simple = new SimpleDateFormat(format);
        String endDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " 23:59";
        String beginDate = simple.format(new Date(new Date().getTime() - 3600000 * 24 * 7));
        Struts2Utils.setRequestAttribute("beginDate", beginDate);
        Struts2Utils.setRequestAttribute("endDate", endDate);
        Struts2Utils.setRequestAttribute("scope", request.getParameter("id"));
        return "common";
    }

    @Override
    public Event getModel() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String list() throws Exception {

        String dimension = request.getParameter("dimension");
        String resIdSearchScope = request.getParameter("resId");
        String resIdAllScope = (resIdSearchScope == null || resIdSearchScope.equals("")) ? "" : resIdSearchScope;
        //查询条件
        String level = request.getParameter("level");
        String status1 = request.getParameter("status");
        String beginDate = request.getParameter("beginDate");
        String endDate = request.getParameter("endDate");
        String eventTypeId = request.getParameter("eventTypeId");
        String confirmtype = request.getParameter("confirmtype");
        String confirmer = request.getParameter("confirmer");
        Condition condition = new Condition();
        Map<String, String> map = new HashMap<String, String>();
        //当前用户可见资源范围
        List<Long> authScopeList = UserFunctionValidate.getResIdListForUser(FunctionConstants.VIEW_RES);
        StringBuffer resIds = new StringBuffer();
        if (authScopeList != null && authScopeList.size() != 0) {
            for (Long resId : authScopeList) {
                resIds.append(resId).append(",");
            }
            resIds.delete(resIds.lastIndexOf(","), resIds.length());
        }
        if (resIds.toString() != null && !resIds.toString().equals("")) {
            String userId = UserUtil.getInstance().getCurrentUserId();
            if (!UserUtil.getInstance().isSysAdmin(userId) && !UserUtil.getInstance().isGuest(userId)) {//guest用户有全部数据的查看权限
                if (resIdAllScope.equals("")) {
                    resIdAllScope = resIds.toString();
                }
            }
        } else {
            JSONObject json = new JSONObject();
            json.element("iTotalRecords", 0);
            json.element("iTotalDisplayRecords", 0);
            JSONArray array = new JSONArray();
            json.element("aaData", array);
            renderText(json.toString());
            return null;
        }
        if (level != null && !level.equals("")) {
            map.put("level_", level);
        } else {
            map.put("level_", "-1");
        }
        if (eventTypeId != null && !eventTypeId.equals("")) {
            map.put("res_type_id", eventTypeId);
        }
        if (status1 != null && !status1.equals("")) {
            map.put("status", status1);
        } else {
            map.put("status", "-1");
        }
        if (beginDate != null && !beginDate.equals("")) {
            map.put("beginDate", beginDate);
        }
        if (endDate != null && !endDate.equals("")) {
            map.put("endDate", endDate);
        }
        if (confirmtype != null && !confirmtype.equals("")) {
            map.put("confirm_type", confirmtype);
        }
        if (confirmer != null && !confirmer.equals("")) {
            map.put("confirmer", "'" + confirmer + "'");
        }
        //资源ID条件
        if (!resIdAllScope.equals("")) {
            map.put("resIds", resIdAllScope);
        }
        map.put("CATALOG", String.valueOf(EventConstants.CATALOG_FAULTEVENT));
        map.put("filter_event_id", null);
        condition.setWhere(map);
        //排序
        Map<String, String> orderMap = new HashMap<String, String>();
        String order = request.getParameter("sSortDir_0");
        String col = request.getParameter("mDataProp_" + request.getParameter("iSortCol_0"));
        if (!col.equals("checkbox")) {
            orderMap.put(col, order);
        }
        //默认按时间降序
        if (orderMap.isEmpty()) {
            //orderMap.put("occurTime", "desc");
        }
        Page<EventBean> page = new Page<EventBean>();
        page.setOrder(orderMap);
        page.setPageNo(Integer.valueOf(request.getParameter("iDisplayStart")) / Integer.valueOf(request.getParameter("iDisplayLength")) + 1);
        page.setPageSize(Integer.valueOf(request.getParameter("iDisplayLength")));
        Page<EventBean> aaData = eventService.findEventByPage(page, condition, dimension);
        String format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat simple = new SimpleDateFormat(format);
        JSONObject json = new JSONObject();
        json.element("iTotalRecords", page.getTotal());
        json.element("iTotalDisplayRecords", page.getTotal());
        JSONArray array = new JSONArray();
        for (EventBean eventBean : aaData.getRows()) {
            JSONObject obj = new JSONObject();
            obj.element("checkbox", "<div align='center'><input type='checkbox' name='dt_check' id='dt_check' value='" + eventBean.getEvent().getId() + "'></div>");
            obj.element("id", eventBean.getEvent().getId());
            //寻找父资源
            Res parent = null;
            List<ResBean> resBeans = RelationHelper.parents(eventBean.getEvent().getResId());
            if (resBeans.size() > 0) {
                parent = resBeans.get(0).res();
            }
            StringBuffer parentNameValue = new StringBuffer("");
            parentNameValue.append(parent == null ? "" : parent.getName() + "/");
            parentNameValue.append(eventBean.getResName());
            obj.element("resName", parentNameValue.toString());

            obj.element("eventTypeName", eventBean.getEventTypeName());
            obj.element("msg", "<a href='event-view!view.action?id=" + eventBean.getEvent().getId() + "' target='_blank'>" + eventBean.getEvent().getMsg() + "</a>");
            //事件级别
            obj.element("level", eventBean.getEvent().getLevel());
            obj.element("levelName", "<div class='eventlevel" + eventBean.getEvent().getLevel() + "' title='" + EventConstants.getLevelDesc(eventBean.getEvent().getLevel()) + "'></div>");
            obj.element("occurTime", simple.format(eventBean.getEvent().getOccurTime()));
            obj.element("status", eventBean.getEvent().getStatus());
            obj.element("statusName", "<div class='status" + eventBean.getEvent().getStatus() + "' title='" + EventConstants.getStatusDesc(eventBean.getEvent().getStatus()) + "'></div>");
            obj.element("lastOccurTime", eventBean.getLastOccurTime() == null ? "" : eventBean.getLastOccurTime());
            //查询清除人信息
            Long id = eventBean.getEvent().getId();
            Event confirm = eventService.getEventById(id);
            if (eventBean.getEvent().getStatus().intValue() == 2)
                /*	if(eventBean.getEvent().getConfirmType() == 1 || eventBean.getEvent().getConfirmType().equals("1"))
                	{
                		obj.element("confirmer", confirm.getConfirmer() != null ? confirm.getConfirmer() : "system");
                	}
                	else{
                		obj.element("confirmer","system");
                	}*/
                //obj.element("confirmer", eventBean.getEvent().getConfirmer() != null ? ((Object) (eventBean.getEvent().getConfirmer())) : "system");
                obj.element("confirmer", confirm.getConfirmer() != null ? confirm.getConfirmer() : "system");
            array.add(obj);
        }
        json.element("aaData", array);
        renderText(json.toString());
        return null;
    }

    public String ackAndConfirmDetails() {
        String format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat simple = new SimpleDateFormat(format);
        Long id = Long.parseLong(Struts2Utils.getParameter("id"));
        Event event = eventService.getEventById(id);
        Map<String, String> map = new HashMap<String, String>();
        if (event.getConfirmType() != null && event.getConfirmType().equals(EventConstants.CONFIRM_TYPE_USER)) {
            map.put("confirm", event.getConfirmer() == null ? "" : (UserUtil.getInstance().getUserById(event.getConfirmer()) == null ? event.getConfirmer() + "此用户已删除" : UserUtil.getInstance().getUserById(event.getConfirmer()).getFullName()));
        } else {
            map.put("confirm", event.getConfirmer() == null ? "" : "system");
        }
        map.put("ack", event.getAckUser() == null ? "" : (UserUtil.getInstance().getUserById(event.getAckUser()) == null ? event.getAckUser() + "此用户已删除" : UserUtil.getInstance().getUserById(event.getAckUser()).getFullName()));
        map.put("ip", resCache.get(event.getResId()).getIp());
        map.put("count", event.getCount() == null ? "" : String.valueOf(event.getCount()));
        map.put("ackTime", event.getAckTime() == null ? "" : simple.format(event.getAckTime()));
        map.put("confirmTime", event.getConfirmTime() == null ? "" : simple.format(event.getConfirmTime()));
        map.put("lastOccurTime", event.getLastOccurTime() == null ? "" : simple.format(event.getLastOccurTime()));
        Struts2Utils.renderJson(map);
        return null;
    }

    @Override
    public String input() throws Exception {
        return "null";
    }

    @Override
    public String save() throws Exception {
        return null;
    }

    @Override
    public String delete() throws Exception {
        return null;
    }

    @Override
    protected void prepareModel() throws Exception {
        // TODO Auto-generated method stub

    }

}
